<template>
    <div>
        <div class="ai-card" v-if="isAwake">
            <div class="voice-recorder">
                <div class="sound-wave">
                    <div v-for="(bar, index) in waveBars" :key="index" class="wave-bar" :style="{
                        height: `${bar.height}px`,
                        backgroundColor: bar.color,
                        animationDelay: `${bar.delay}s`
                    }"></div>
                </div>
                <div class="recording-text">您请说...</div>
            </div>
            <!-- <div class="close">
                <el-icon size="40" color="#fff" @click="close">
                    <Close />
                </el-icon>
            </div> -->
        </div>
        <div class="ai-card" v-if="!isAwake && transcriptValue">
            <div class="chat-content">
                <div class="content" ref="chatContent">
                    <div class="" :class="[item.modelReply ? 'right-chat' : 'left-chat']" v-for="(item) in chatList"
                        :key="item.questionId">
                        <img :src="getImage(`/src/assets/image/${item.modelReply ? 'ai' : 'user'}.png`)" alt="">
                        <div>
                            <div v-html="item.modelReply ? item.modelReply : item.userQuestion">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="input">
                    <div class="input-box">
                        <el-input v-model="inputValue" style="width: 100%;height: 100%;font-size: 16px;" resize="none"
                            type="textarea" placeholder="输入您的问题" />
                    </div>
                    <div class="send" @click="send">
                        发送
                    </div>
                </div>
            </div>
            <div class="close">
                <el-icon size="40" color="#fff" @click="close">
                    <Close />
                </el-icon>
            </div>
        </div>

    </div>
</template>

<script setup>
import 'animate.css/animate.min.css';
import { ref, onMounted, onUnmounted, defineProps, watch, defineEmits, nextTick } from 'vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify' // 安全处理HTML
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();

const emit = defineEmits(['close']);
const getImage = (url) => {
    return new URL(url, import.meta.url).href;
};
const props = defineProps({
    transcriptValue: {
        type: String,
        default: ''
    },
    isAwake: {
        type: Boolean,
        default: false
    },
    showChat: {
        type: Boolean,
        default: false
    }
})
const waveBars = ref([
    { height: 30, color: 'rgba(74, 141, 248, 0.8)', delay: 0 },
    { height: 50, color: 'rgba(74, 141, 248, 0.9)', delay: 0.15 },
    { height: 70, color: 'rgba(74, 141, 248, 1)', delay: 0.3 },
    { height: 90, color: 'rgba(74, 141, 248, 0.9)', delay: 0.45 },
    { height: 70, color: 'rgba(74, 141, 248, 0.8)', delay: 0.6 },
    { height: 50, color: 'rgba(74, 141, 248, 0.7)', delay: 0.75 },
    { height: 30, color: 'rgba(74, 141, 248, 0.6)', delay: 0.9 }
])

let animationFrame = null
const inputValue = ref('')
const chatList = ref([])
const chatContent = ref(null);
const pagePath = ref('');
const session = ref(1);
const sessionIdIndex = ref(1);

watch(() => props.transcriptValue, (newValue) => {
    console.log(newValue);

    if (!props.isAwake) {
        inputValue.value = newValue;
        send();
    }
})

watch(route, () => {
    console.log(route);
    emit('close');
})


const nextRouyter = (path) => {
    console.log('跳转');
    router.push({
        path,
    })
}

const animateWave = () => {
    const time = Date.now() / 1000
    waveBars.value = waveBars.value.map((bar, index) => {
        // 使用正弦函数创建更自然的波浪效果
        const waveHeight = Math.sin(time * 2 + index * 0.5) * 20 + 50
        const opacity = 0.6 + Math.abs(Math.sin(time * 1.5 + index * 0.3)) * 0.4
        return {
            ...bar,
            height: Math.max(30, Math.min(120, waveHeight)),
            color: `rgba(74, 141, 248, ${opacity})`
        }
    })
    animationFrame = requestAnimationFrame(animateWave)
}
// 使用 Fetch API 处理 SSE 流
function sendAIMessage(message) {
    if (sessionIdIndex.value >= 10) {
        session.value += 1;
        sessionIdIndex.value = 1;
    } else {
        sessionIdIndex.value += 1;
    }
    const params = {
        userId: 1,
        sessionId: session.value,
        message: message,
        currentLocation: null,
        targetLocation: null
    };

    fetch(import.meta.env.VITE_APP_AI_URL + '/ai/chat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'text/event-stream'
        },
        body: JSON.stringify(params)
    })
        .then(async (response) => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 获取可读流
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';

            chatList.value.push({
                "modelReply": '',
                questionId: chatList.value.length
            });

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                buffer += decoder.decode(value, { stream: true });

                // 处理事件流（按\n\n分割）
                const lines = buffer.split('\n\n');
                buffer = lines.pop(); // 剩余部分放回缓冲区

                for (const line of lines) {

                    const lastMessage = chatContent.value.lastElementChild;
                    if (lastMessage) {
                        lastMessage.scrollIntoView({ behavior: 'smooth' });
                    }
                    if (line.startsWith('data:')) {
                        let content = line.trim().replace(/data:/g, '');
                        console.log('收到AI响应:', content);

                        // 处理跳转
                        if (content.includes('page')) {
                            let data = JSON.parse(content);
                            content = data.content;
                            pagePath.value = data.page;
                        }

                        // 在这里更新UI显示
                        chatList.value[chatList.value.length - 1].modelReply = chatList.value[chatList.value.length - 1].modelReply + content;
                    }
                }

                inputValue.value = '';
            }

            // 使用  markdown格式 处理文本
            chatList.value[chatList.value.length - 1].modelReply = parseMarkdown(chatList.value[chatList.value.length - 1].modelReply);
            const lastMessage = chatContent.value.lastElementChild;
            if (lastMessage) {
                lastMessage.scrollIntoView({ behavior: 'smooth' });
            }
            if (!pagePath.value) return
            setTimeout(() => {
                nextRouyter(pagePath.value);
            }, 2000);
        })
        .catch(error => {
            console.error('请求失败:', error);
        });
}

function parseMarkdown(mdContent) {
    // 先解析Markdown为HTML
    const rawHtml = marked.parse(mdContent || '')
    // 再净化HTML防止XSS攻击
    return DOMPurify.sanitize(rawHtml)
}
const send = () => {
    if (inputValue.value.trim() == '') {
        return;
    }
    chatList.value.push({
        "userQuestion": inputValue.value,
        questionId: chatList.value.length
    });


    // 调用示例
    sendAIMessage(inputValue.value);
}

const close = () => {
    emit('close');
}
onMounted(() => {
    // 配置 marked
    marked.setOptions({
        breaks: true,       // 转换换行符为 <br>
        gfm: true,          // 支持GitHub风格的Markdown
        smartypants: true   // 智能标点转换
    })
    animationFrame = requestAnimationFrame(animateWave)
})

onUnmounted(() => {
    cancelAnimationFrame(animationFrame)
})

</script>

<style scoped lang="scss">
.ai-card {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
}

.voice-recorder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px;
    border-radius: 20px;
    width: 80%;
    max-width: 500px;
    transform: translateY(-50%);
}

.sound-wave {
    display: flex;
    align-items: flex-end;
    justify-content: center;
    height: 200px;
    gap: 10px;
    margin-bottom: 30px;
}

.wave-bar {
    width: 20px;
    border-radius: 10px;
    transition: all 0.3s ease-out;
    animation: wave-animation 2s infinite ease-in-out;
}

@keyframes wave-animation {

    0%,
    100% {
        transform: scaleY(0.9) translateY(10px);
    }

    50% {
        transform: scaleY(1.1) translateY(-5px);
    }
}

.recording-text {
    font-family: 'Arial', sans-serif;
    font-size: 24px;
    color: #fff;
    font-weight: 500;
    letter-spacing: 1px;
}

.chat-content {
    width: 50%;
    height: 80%;
    padding: 20px;
    display: flex;
    flex-direction: column;

    .content::-webkit-scrollbar-track {}

    .content::-webkit-scrollbar {
        width: 0px;
    }

    .content::-webkit-scrollbar-thumb {
        background: rgba(21, 91, 202, 0.4) !important;
        border-radius: 25px !important;
    }

    .content {
        flex: 1;
        margin-bottom: 40px;
        overflow: hidden;
        overflow-y: scroll;

        >div {
            display: flex;
            align-items: flex-start;
            margin-bottom: 40px;

            img {
                width: 20px;
                height: 20px;
            }

            >div {
                background: green;
                padding: 5px 10px;
                margin: 0 20px;
                border-radius: 6px;
                max-width: 400px;
                font-size: 16px;
                color: rgba(255, 255, 255, .7);
            }
        }

        .left-chat {
            flex-direction: row;
            flex-direction: row-reverse;
        }
    }

    .input {
        display: flex;
        width: 100%;
        align-items: center;

        .input-box {
            width: 100%;
        }

        .send {
            width: 100px;
            height: 100%;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            margin-left: 20px;
            background: linear-gradient(90deg, rgba(5, 64, 173, 1) 0%, rgba(12, 85, 232, 1) 48.8%, rgba(9, 64, 173, 1) 100%);
            color: #fff;
            cursor: pointer;
        }
    }
}

.close {
    position: absolute;
    right: 80px;
    top: 80px;
    cursor: pointer;
}
</style>